package com.gome.boot.common.interceptor;

import com.gome.boot.common.annotation.aspect.TimeAspect;
import com.gome.boot.common.logger.BaseLogger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.weaver.reflect.ReflectionWorld;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 默认的方法调用时间统计拦截器.
 * <br/>建议只在必要的地方添加拦截，避免影响接口调用性能.
 *
 * @author baoxiufeng
 */
@Component
@Aspect
@Order(0)
@ConditionalOnClass({Aspect.class, ReflectionWorld.class})
public class DefaultTimeInterceptor extends BaseLogger {

    @Around("@within(timeAspect) || @annotation(timeAspect)")
    public Object timeAround(ProceedingJoinPoint jp, TimeAspect timeAspect) throws Throwable {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        Object obj = null;
        try {
            long stime = System.currentTimeMillis();
            obj = jp.proceed(jp.getArgs());
            if (logger.isInfoEnabled()) {
                logger.info("[{}] Execute total time:[{}]ms", methodName, System.currentTimeMillis() - stime);
            }
        } catch (Throwable e) {
            logger.error("[" + methodName + "] Execute exception.", e);
            throw e;
        }
        return obj;
    }
}
